package cn.wolfcode.shop.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


/**
 * 上传工具
 *
 * @author Administrator
 *
 */
public class UploadUtil {

	/**
	 * 处理文件上传
	 * @param basePath
	 *            存放文件的目录的绝对路径 servletContext.getRealPath("/upload")
	 * @return
	 */

	/*public static String getBasePath(HttpServletRequest request){
		//String realPath = request.getServletContext().getRealPath("/") 从request中取，得到webapp路径。
		String realPath = request.getServletContext().getRealPath("/static/image") ; //拼接文件夹
	return realPath;

	}*/


	public static String upload(MultipartFile file, String basePath) {
		String orgFileName = file.getOriginalFilename();//文件原始全名
		String fileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(orgFileName);  //UUID名称+.+扩展名
		try {
			File targetFile = new File(basePath, fileName);
			FileUtils.writeByteArrayToFile(targetFile, file.getBytes());

			//把文件同步到公共文件夹
			File publicFile=new File(basePath,fileName);
			FileUtils.writeByteArrayToFile(publicFile, file.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}
}



















